package com.heima.wemedia.builder;

import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;

public class ArticleDtoBuilder {
    private ArticleDto articleDto = new ArticleDto();
    private WmNews wmNews;
    private WmUserMapper wmUserMapper;
    private WmChannelMapper wmChannelMapper;

    public ArticleDtoBuilder(WmNews wmNews,WmUserMapper wmUserMapper,WmChannelMapper wmChannelMapper){
        this.wmNews = wmNews;
        this.wmUserMapper = wmUserMapper;
        this.wmChannelMapper = wmChannelMapper;
    }

    public ArticleDtoBuilder buildBeanCopy(){
        BeanUtils.copyProperties(wmNews,articleDto);
        return this;
    }

    public ArticleDtoBuilder buildAuthor(){
        if (wmNews.getUserId() != null){
            articleDto.setAuthorId(wmNews.getUserId());
            WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
            articleDto.setAuthorName(wmUser.getName());
        }
        return this;
    }

    public ArticleDtoBuilder buildChannel(){
        if (wmNews.getChannelId() != null){
            WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
            articleDto.setChannelName(wmChannel.getName());
        }
        return this;
    }

    public ArticleDtoBuilder buildBasic(){
        articleDto.setLayout(wmNews.getType());
        articleDto.setCreatedTime(new Date());
        articleDto.setCollection(0);
        articleDto.setComment(0);
        articleDto.setViews(0);
        articleDto.setLikes(0);
        if(wmNews.getArticleId() != null){
            articleDto.setId(wmNews.getArticleId());
        }

        return this;
    }

    public ArticleDto build(){
        return this.articleDto;
    }
}
